package com.tedu.bill;

/**
 * Author：毕龙
 * Date: 2024/4/2 19:29
 */
public class TestQuestion14 {
    public static void main(String[] args) {
        getNum(3,3);
    }

    //螺旋填数
    public static void getNum(int m, int n){
        //二维数组的大小 m行 n列
        int[][] arr = new int[m][n];
        //声明一个变量
        int num = 0;
        //声明4个变量
        int left = 1;
        int right = 2;
        int down = 3;
        int up = 4;
        //声明一个变量 用来确定方向
        int direction = 2;
        //声明两个变量
        int i = 0;
        int j = 0;//表示列

        //做一个循环
        while (num <= n*m ){
            num ++;
            //判断如果是从左到右执行
            if(direction  == right && j < n && arr[i][j] == 0){
                arr[i][j] = num;
                j++;
            }
            //当j等于n
            if(j == n || arr[i][j] != 0  ){
                // 为了不放列出现下标越界异常
                j--;
                //向下走一行
                i++;
                //方向定向下
                direction = 3;
                num++;
            }
            //判断向下
            if(direction == down && i < m && arr[i][j] == 0){
                arr[i][j] = num;
                i++;

            }

            //当i等于m
            if(i == m || arr[i][j] != 0 ){
                i--;
                j--;
                //方向定向下
                direction = 1;
                num++;
            }

            if(direction == left && j>= 0 && arr[i][j] == 0) {
                arr[i][j] = num;
                j--;
            }

            //当j等于-1
            if(j == -1 || arr[i][j] != 0){
                j++;
                //向下走一行
                i--;
                //方向定向下
                direction = 4;
                num++;
            }
            if(direction == up && i >= 0 && arr[i][j] == 0){
                arr[i][j] = num;
                i--;
            }

            if(arr[i][j] != 0 ){
                direction = 2;
                j++;
                i++;
            }

        }


        //遍历
        for (int k = 0; k < arr.length; k++) {
            for (int l = 0; l < arr[k].length; l++) {
                System.out.print(arr[k][l]+"\t");
            }
            System.out.println();
        }

    }
}
